<?php

namespace app\admin\controller\financing;

use app\common\controller\Backend;
use think\Db;
use think\Env;
//use think\exception\ValidateException;

/**
 * 提现/兑换审核
 *
 * @icon fa fa-table
 * @remark 当一个页面上存在多个Bootstrap-table时该如何控制按钮和表格
 */
class Logs extends Backend
{
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Bigss;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        if (isset(request()->param()['big_id'])){
            $id = request()->param()['big_id'];
        }else{
            $id = 0;
        }

        //$this->view->assign("id", $id);
        $this->assignconfig('id',$id);
        return $this->view->fetch();
    }

    public function table1()
    {
        $this->model = model('Bigss');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'big' => function ($query) {
                        $query->withField('id,code,name');
                    }
                ])
                ->where($where)
                ->where('bigss.type',1)
                ->order('bigss.id', 'desc')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function table2()
    {
        $this->model = model('Bigss');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'big' => function ($query) {
                        $query->withField('id,code,name');
                    }
                ])
                ->where($where)
                ->where('bigss.type',2)
                ->order('bigss.id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $list->items()[$k]['moneys'] = floor(($v->amount*1.5)*100)/100;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function table3()
    {
        $this->model = model('Check');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'order' => function ($query) {
                        $query->withField('id,code');
                    },
                    'info' => function ($query) {
                        $query->withField('id,name');
                    },
                ])
                ->where($where)
                ->order('id', 'desc')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }


    /**
     * 审核操作
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     */
    public function close($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $type = request()->param()['type'];
            //事务开始
            Db::startTrans();
            if ($type == 1){
                $big_arr = Db::table('fa_big')
                    ->where('id',$row->big_id)
                    ->find();

                if (empty($big_arr)){
                    $this->error(__('合伙人数据为空'));
                }

                $update = Db::table('fa_big_logs')
                    ->where('id',$ids)
                    ->update([
                        'status' => 1,
                        'update_time' => time(),
                    ]);

                $updateb = Db::table('fa_big')
                    ->where('id',$row->big_id)
                    ->update([
                        'already' => $big_arr['already']+$row->amount,
                        'update_time' => time(),
                    ]);

                $updates = 1;
                $insert = 1;
            }elseif ($type == 2){
                $user_arr = Db::table('fa_big')
                    ->alias('a')
                    ->field('a.already,b.id,b.money')
                    ->join('fa_users b','a.phone=b.phone','left')
                    ->where('a.id',$row->big_id)
                    ->find();

                if (empty($user_arr)){
                    $this->error(__('储值卡数据为空'));
                }


                $money = floor($row->amount*1.5*100)/100;
                $update = Db::table('fa_big_logs')
                    ->where('id',$ids)
                    ->update([
                        'status' => 1,
                        'update_time' => time(),
                    ]);

                $updates = Db::table('fa_users')
                    ->where('id',$user_arr['id'])
                    ->update([
                        'money' => $money+$user_arr['money'],
                        'update_time' => time(),
                    ]);

                $updateb = Db::table('fa_big')
                    ->where('id',$row->big_id)
                    ->update([
                        'already' => $user_arr['already']+$row->amount,
                        'update_time' => time(),
                    ]);

                $insert = Db::table('fa_card_log')
                    ->insertGetId([
                        'user_id' => $user_arr['id'],
                        'money' => $money,
                        'pay' => 6,
                        'create_time' => time(),
                        'type' => 1,
                    ]);

            }else{
                $this->error(__('类型错误'));
            }


            if (($update !== false) && ($updates !== false) && ($updateb !== false) && ($insert !== false)){
                //事务提交
                Db::commit();
                $this->success("成功", null, ['id' => $ids]);
            }else{
                //事务回滚
                Db::rollback();
                $this->error(__('失败'));
            }


        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 驳回操作
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     */
    public function reject($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $big_arr = Db::table('fa_big')
                ->where('id',$row->big_id)
                ->find();

            if (empty($big_arr)){
                $this->error(__('合伙人数据为空'));
            }

            //事务开始
            Db::startTrans();

            $update = Db::table('fa_big_logs')
                ->where('id',$ids)
                ->update([
                    'status' => 2,
                    'update_time' => time(),
                ]);

            if ($row->types == 1){
                $updates = Db::table('fa_big')
                    ->where('id',$row->big_id)
                    ->update([
                        'consumption' => $row->money+$big_arr['consumption'],
                        'can' => $row->amount+$big_arr['can'],
                        'update_time' => time(),
                    ]);
            }elseif($row->types == 2){
                $updates = Db::table('fa_big')
                    ->where('id',$row->big_id)
                    ->update([
                        'group' => $row->money+$big_arr['group'],
                        'can' => $row->amount+$big_arr['can'],
                        'update_time' => time(),
                    ]);
            }else{
                $updates = 1;
            }




            if (($update !== false) && ($updates !== false)){
                //事务提交
                Db::commit();
                $this->success("成功", null, ['id' => $ids]);
            }else{
                //事务回滚
                Db::rollback();
                $this->error(__('失败'));
            }


        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 审核
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     */
    public function check($ids)
    {

        if ($this->request->isAjax()) {
            $order_arr = Db::table('fa_check')
                ->alias('a')
                ->field('a.*,b.big_id,b.info_id,b.code')
                ->join('fa_diagnosis_order b','a.order_id=b.id','left')
                ->where('a.id',$ids)
                ->find();

            //事务开始
            Db::startTrans();
            $update = 1;
            $insert = 1;
            $updates = 1;
            $inserts = 1;
            if (!empty($order_arr['big_id'])){
                $big_arr = Db::table('fa_big')
                    ->where('id',$order_arr['big_id'])
                    ->find();

                if (!empty($big_arr)){
                    $consumption = $big_arr['consumption']+$order_arr['moneys'];
                    $group_can = floor($big_arr['group']*0.05*100)/100;
                    if ($consumption < 1000000){
                        $ratio = '10%';
                        $can = floor($consumption*0.1*100)/100;
                    }elseif (($consumption >= 1000000) && ($consumption < 3000000)){
                        $ratio = '15%';
                        $can = floor($consumption*0.15*100)/100;
                    }elseif ($consumption >= 3000000){
                        $ratio = '20%';
                        $can = floor($consumption*0.2*100)/100;
                    }


                    //直客收益
                    $update = Db::table('fa_big')
                        ->where('id',$big_arr['id'])
                        ->update([
                            'consumption' => $consumption,
                            'can' => $can+$group_can,
                            'update_time' => time(),
                        ]);

                    $insert = Db::table('fa_big_logss')
                        ->insertGetId([
                            'big_id' => $big_arr['id'],
                            'info_id' => $order_arr['info_id'],
                            'code' => $order_arr['code'],
                            'moneys' => $order_arr['money'],
                            'amount' => $order_arr['moneys'],
                            'create_time' => time(),
                            'type' => 1,
                            'count' => $order_arr['count'],
                        ]);

                    if (!empty($big_arr['pid'])){
                        $pid_arr = Db::table('fa_big')
                            ->where('id',$big_arr['pid'])
                            ->find();

                        $group = $pid_arr['group']+$order_arr['moneys'];
                        $group_cans = floor($group*0.05*100)/100;
                        if ($pid_arr['consumption'] < 1000000){
                            $ratio = '10%';
                            $cans = floor($pid_arr['consumption']*0.1*100)/100;
                        }elseif (($pid_arr['consumption'] >= 1000000) && ($pid_arr['consumption'] < 3000000)){
                            $ratio = '15%';
                            $cans = floor($pid_arr['consumption']*0.15*100)/100;
                        }elseif ($pid_arr['consumption'] >= 3000000){
                            $ratio = '20%';
                            $cans = floor($pid_arr['consumption']*0.2*100)/100;
                        }

                        //团队收益
                        $updates = Db::table('fa_big')
                            ->where('id',$big_arr['pid'])
                            ->update([
                                'group' => $group,
                                'can' => $cans+$group_cans,
                                'update_time' => time(),
                            ]);

                        $inserts = Db::table('fa_big_logss')
                            ->insertGetId([
                                'big_id' => $big_arr['pid'],
                                'info_id' => $order_arr['info_id'],
                                'code' => $order_arr['code'],
                                'moneys' => $order_arr['money'],
                                'amount' => $order_arr['moneys'],
                                'create_time' => time(),
                                'type' => 2,
                                'count' => $order_arr['count'],
                                'subordinate' => $big_arr['id'],
                            ]);
                    }


                }
            }

            $updatet = Db::table('fa_check')
                ->where('id',$ids)
                ->update([
                    'is_check' => 1,
                    'update_time' => time(),
                ]);


            if (($updatet !== false) && ($update !== false) && ($insert !== false) && ($updates !== false) && ($inserts !== false)){
                //事务提交
                Db::commit();
                $this->success("成功", null, ['id' => $ids]);
            }else{
                //事务回滚
                Db::rollback();
                $this->error(__('失败'));
            }


        }
        //$this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }



}
